package com.jcl.cloud.services.crawler.search.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StringUtil {


    private static Logger logger = LoggerFactory.getLogger(StringUtil.class);

    public static String getStrWithRegex(String str, String regex) {
        String retStr = "";

        int times = 0;
        if(StringUtils.isNotBlank(str)){

            Pattern pattern = Pattern.compile(regex);
            Matcher matcher = pattern.matcher(str);
            while (true){
                times++;
                if (matcher.find()) {
                    retStr = matcher.group(1);
                    if(StringUtils.isNotBlank(retStr)){
                        break;
                    }
                }else {
                    if(times > 10){
                        break;
                    }
                }
            }
        }
        return retStr;
    }

    public static String getCompanyName(String str) {
        String strA = str.split("公司:")[1].split("行业:")[0].replaceAll(" ", "");
        return strA;
    }


    public static String getCityName(String str) {
        try {
            if (str.contains("-")) {
                return str.split("-")[0];
            } else {
                return str;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }


    public static String[] getSalary(String str) {
        String[] salaryArr = new String[2];
        double start = 0;
        double end = 0;
        if (str.contains("元/月")) {
            str = str.replaceAll("元/月", "");
            if (str.contains("及以上")) {

                str = str.replaceAll("及以上", "");
                start = Double.valueOf(str) / 1000;
                end = start;
            } else {
                String[] salaryTemp = str.split("-");
                start = Double.valueOf(salaryTemp[0]) / 1000;
                end = Double.valueOf(salaryTemp[1]) / 1000;
            }

        } else if (str.contains("万元/年")) {
            str = str.replaceAll("万元/年", "");
            String[] salaryTemp = str.split("-");
            start = Double.valueOf(salaryTemp[0]) * 10 / 12;
            end = Double.valueOf(salaryTemp[1]) * 10 / 12;
        }

        salaryArr[0] = String.valueOf(Math.round(start));
        salaryArr[1] = String.valueOf(Math.round(end));

        return salaryArr;
    }


    public static List<Map<String, String>> wd2MapQcwy(String workDetail) {

        List<Map<String, String>> worksList = new ArrayList<>();
        try {
            String[] worksArr = workDetail.split("\\*\\*\\*\\*\\*\\*\\*\\*\\*\\*\\*\\*\\*\\*\\*\\*\\*\\*\\*\\*");
            for (String str : worksArr) {
                Map map = new HashMap();
                String[] arr1 = str.trim().split("职位:");
                String[] arr2 = arr1[0].split("——公司:");
                String[] arr3 = arr2[0].split("至");
                String start_date = arr3[0].replaceAll("\r\n", "");

                map.put("start_date", start_date);
                String end_date = "";
                if (arr3[1].contains("今")) {
                    end_date = "至" + arr3[1].replaceAll("\r\n", "");
                } else {
                    end_date = arr3[1].replaceAll("\r\n", "");
                }

                map.put("end_date", end_date);

                String company = arr2[1].split("\\(")[0].replaceAll("\r\n", "");

                map.put("company", company);


                String[] arr4 = arr1[1].split("工作描述：");
                String position = arr4[0].replaceAll("\r\n", "");

                map.put("position", position);

                String duty = arr4[1];
                map.put("duty", duty);

                worksList.add(map);
            }
        } catch (Exception e) {
            logger.error("解析work_detail字段发生异常；", e);
        }
        return worksList;
    }


    public static List<Map<String, String>> wd2MapZlzp(String workDetail) {
        List<Map<String, String>> worksList = new ArrayList<>();


        try {
            JSONArray ja = JSON.parseArray(workDetail);
            for (int i = 0; i < ja.size(); i++) {
                Map map = new HashMap();
                String start_date = ja.getJSONObject(i).getString("DateStart");
                String end_date = ja.getJSONObject(i).getString("DateEnd");
                String company = ja.getJSONObject(i).getString("CompanyName");
                String position = ja.getJSONObject(i).getString("JobTitle");
                String duty = ja.getJSONObject(i).getString("WorkDescription");

                map.put("start_date", start_date.split(" ")[0]);
                map.put("end_date", end_date.split(" ")[0]);
                map.put("company", company);
                map.put("position", position);
                map.put("duty", duty);

                worksList.add(map);
            }
        } catch (Exception e) {
            logger.error("解析work_detail字段发生异常；", e);
        }
        return worksList;
    }


    public static List<Map<String, String>> edu2MapQcwy(String eduStr) {
        List<Map<String, String>> edusList = new ArrayList<>();
        try {
            String[] edusArr = eduStr.split("\\*\\*\\*\\*\\*\\*\\*\\*\\*\\*\\*\\*\\*\\*\\*\\*\\*\\*\\*\\*");
            for (String str : edusArr) {
                Map map = new HashMap();
                String[] eduArr = str.trim().split("\r\n");
                if (eduArr.length > 0) {
                    String[] arr1 = eduArr[0].split("——");
                    String[] arr2 = arr1[0].split("至");
                    String start_date = arr2[0].replaceAll("\"", "");
                    map.put("start_date", start_date);
                    String end_date = arr2[1];
                    map.put("end_date", end_date);
                    String school = arr1[1];
                    map.put("school", school);
                    String[] arr3 = eduArr[1].split(" ");
                    String major = arr3[0];
                    map.put("major", major);
                    String degree = arr3[1];
                    map.put("degree", degree);
                }

                edusList.add(map);
            }
        } catch (Exception e) {
            logger.error("解析前程无忧教育经历字段发生异常；", e);
        }
        return edusList;
    }


    public static List<Map<String, String>> pd2MapQcwy(String projectDetail) {
        List<Map<String, String>> projectsList = new ArrayList<>();

        try {
            String[] projectsArr = projectDetail.split("\\*\\*\\*\\*\\*\\*\\*\\*\\*\\*\\*\\*\\*\\*\\*\\*\\*\\*\\*\\*");
            for (String str : projectsArr) {
                Map map = new HashMap();
                try {
                    String[] arr1 = str.split("项目描述：");
                    String[] arr2 = arr1[0].trim().split("\r\n");
                    String[] arr3 = arr2[0].split("——");
                    String[] arr4 = arr3[0].split("至");
                    String start_date = arr4[0].replaceAll("\"","");
                    map.put("start_date",start_date );
                    String end_date = "";
                    if (arr4[1].contains("今")) {
                        end_date = "至" + arr3[1].replaceAll("\r\n", "");
                    } else {
                        end_date = arr3[1].replaceAll("\r\n", "");
                    }
                    map.put("end_date",end_date );

                    String projectname = arr3[1].replaceAll("\r\n", "").trim();
                    map.put("projectname",projectname);
                    String description = arr1[1];
                    map.put("description",description);



                } catch (Exception e) {
                    logger.error(String.format("项目详细信息：%s    解析前程无忧项目详细信息某一条发生异常；%s",str,e.getMessage()),e);
                }
                projectsList.add(map);
            }
        } catch (Exception e) {
            logger.error(String.format("项目详细信息projectDetail：%s    解析前程无忧项目详细信息发生异常；%s",projectDetail,e.getMessage()),e);
        }

        return projectsList;
    }


    public static List<Map<String, String>> edu2MapZlzp (String eduStr){

        List<Map<String, String>> edusList = new ArrayList<>();

        try {
            JSONArray ja = JSONObject.parseArray(eduStr);

            for(Object object : ja){
                JSONObject jo = (JSONObject)object;
                Map map = new HashMap();

               String start_date = jo.getString("DateStart").split(" ")[0];
               String end_date = jo.getString("DateEnd").split(" ")[0];
               String major = jo.getString("MajorName");
               String degree = code2EduLevel(jo.getString("EducationLevel"));
               String school = jo.getString("SchoolName");

                map.put("start_date",start_date );
                map.put("end_date", end_date);
                map.put("major",major );
                map.put("degree",degree );
                map.put("school",school );

                edusList.add(map);
            }
        } catch (Exception e) {
            logger.error(String.format("解析智联招聘教育经历字段发生异常：%s",e));
        }

        return edusList;
    }



    public static List<Map<String, String>> pd2MapZlzp(String projectDetail) {
        List<Map<String, String>> projectsList = new ArrayList<>();

        try {
            JSONArray ja = JSONObject.parseArray(projectDetail);
            for(Object o:ja){
                Map map = new HashMap();
                JSONObject jo = (JSONObject)o;
                String start_date = jo.getString("DateStart").split(" ")[0];
                String end_date = jo.getString("DateEnd").split(" ")[0];
                String projectname = jo.getString("ProjectName");
                String description = jo.getString("ProjectDescription");
                String duty = jo.getString("ProjectResponsibility");

                map.put("start_date",start_date );
                map.put("end_date",end_date );
                map.put("projectname",projectname );
                map.put("description",description );
                map.put("duty",duty );

                projectsList.add(map);
            }
        } catch (Exception e) {
            logger.error(String.format("解析智联招聘项目经历字段发生异常：%s",e));
        }


        return projectsList;
    }


    public static String code2EduLevel(String code){
        String label = "";

        try {
            if(StringUtils.isBlank(code) ){
                label = "不限";
            }else {
                int c = Integer.valueOf(code.replaceAll(" ",""));
                if(c == 9){
                    label = "初中";
                }

                if(c == 13){
                    label = "中技";
                }

                if(c == 7){
                    label = "高中";
                }

                if(c == 12){
                    label = "中专";
                }

                if(c == 5){
                    label = "大专";
                }

                if(c == 4){
                    label = "本科";
                }

                if(c == 3){
                    label = "硕士";
                }

                if(c == 10){
                    label = "MBA";
                }

                if(c == 11){
                    label = "EMBA";
                }

                if(c == 1){
                    label = "博士";
                }

                if(c == 0){
                    label = "及以上";
                }
            }
        } catch (Exception e) {
            logger.error(String.format("code2EduLevel发生异常：%s",e));
        }


        return  label;
    }




    public static String getApplyDate(String currDate){

        String applyDate = null;
        try {
            Calendar date = Calendar.getInstance();
            String year = String.valueOf(date.get(Calendar.YEAR));

            applyDate = year + "-"+currDate.split(" ")[0];
        } catch (Exception e) {
           logger.error("getApplyDate 发生异常：",e);
        }



        return applyDate;



    }










    //href="/Candidate/ResumeView.aspx?
    public static List<String> getResumeViewUrlList (String html){
        List<String> urlList = new ArrayList<>();
        String regex = "href=\"/Candidate/ResumeView.aspx?(.*?)\"";
        String s = "";
        String url = "";
        String preUrl = "https://ehire.51job.com/Candidate/ResumeView.aspx";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(html);
        while (matcher.find()) {
            s = matcher.group(1);
            url = preUrl + s;
            urlList.add(url);
        }


        return  urlList;

    }





    public static Map salary2MapZlzp(String salary){

        Map<String,String> map = new HashMap<>();
        String desire_salary_start = "";
        String desire_salary_end = "";
        //判断前面需要加几个0
        int len = salary.length();
        int add0Num = 10 - len;
        for(int i = 0;i<add0Num;i++){
            salary = 0+salary;
        }

        String str = "[[\"0000001000\", \"0\", \"1000元/月以下\", \"Below 1000RMB/Month\"], [\"0100002000\", \"0\", \"1000-2000元/月\", \"1000-2000RMB/Month\"], [\"0200104000\", \"0\", \"2001-4000元/月\", \"2001-4000RMB/Month\"], [\"0400106000\", \"0\", \"4001-6000元/月\", \"4001-6000RMB/Month\"], [\"0600108000\", \"0\", \"6001-8000元/月\", \"6001-8000RMB/Month\"], [\"0800110000\", \"0\", \"8001-10000元/月\", \"8001-10000RMB/Month\"], [\"1000115000\", \"0\", \"10001-15000元/月\", \"10001-15000RMB/Month\"], [\"1500125000\", \"0\", \"15000-25000元/月\", \"15000-25000RMB/Month\"], [\"2500199999\", \"0\", \"25000-35000元/月\", \"25000-35000RMB/Month\"], [\"3500150000\", \"0\", \"35000-50000元/月\", \"35000-50000RMB/Month\"], [\"5000170000\", \"0\", \"50000-70000元/月\", \"50000-70000RMB/Month\"], [\"70001100000\", \"0\", \"70000-100000元/月\", \"70000-100000RMB/Month\"], [\"100001150000\", \"0\", \"100000元/月以上\", \"Above 100000RMB/Month\"], [\"0000000000\", \"0\", \"面议\", \"Confidential\"]]";
        JSONArray jsonArray =  JSON.parseArray(str);

        for(Object object:jsonArray){
            JSONArray ja = (JSONArray)object;
            if(salary.equals(ja.getString(0))){
                String salaryScope = ja.getString(2);
                if(salaryScope.equals("1000元/月以下")){
                    desire_salary_start = "1000";
                    desire_salary_end = "1000";
                }else if(salaryScope.equals("100000元/月以上")){
                    desire_salary_start = "100000";
                    desire_salary_end = "100000";
                }else if(salaryScope.equals("面议")){
                    desire_salary_start = "0";
                    desire_salary_end = "0";
                }else {
                    salaryScope = salaryScope.replaceAll("元/月","");

                    String [] salaryArr = salaryScope.split("-");
                    desire_salary_start = salaryArr[0];
                    desire_salary_end = salaryArr[1];
                }
                map.put("desire_salary_start",desire_salary_start );
                map.put("desire_salary_end",desire_salary_end );
                break;
            }
        }
        return map;
    }




    public static String code2SexZlzp(String sexNo){

        String sex = "";
        if(sexNo.equals("1")){
            sex = "男";
        }else if(sexNo.equals("0")){
            sex = "女";
        }

        return  sex;
    }



    public static String ymd2BirthDayZlzp(String birthYear,String birthMonth,String birthDay){
        String BirthDay = "";
        if(birthMonth.length() == 1){
            birthMonth = 0+birthMonth;
        }

        if(birthDay.length() == 1){
            birthDay = 0+birthDay;
        }


        BirthDay = birthYear+"-"+birthMonth+"-"+birthDay;

        return BirthDay;
    }



    public static String workYearsRangeIdToWorkYearsZlzp(String workYearsRangeId){
        String workYear = "";

        try {
            if("00".equalsIgnoreCase(workYearsRangeId)){
                workYear = "1";
            }else {

                int year = Integer.parseInt(workYearsRangeId.substring(0,4));
                int month = Integer.parseInt(workYearsRangeId.substring(4,workYearsRangeId.length()));


                Calendar now = Calendar.getInstance();
                int nowYear = now.get(Calendar.YEAR);
                int nowMonth = now.get(Calendar.MONTH)+1;

                int totalMonths = (nowYear-year)*12 + (nowMonth-month);
                int temp = totalMonths/12;
                workYear = String.valueOf(temp!=0 ? temp:1);
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }


        return  workYear;


    }









    public static List<Map<String, String>> htmlWD2MapQcwy(String source){

        List<Map<String, String>> worksList = new ArrayList<>();
        Document document = Jsoup.parse(source);
        Elements tbodyEles = document.select("tbody:has(tbody:contains(工作描述))");
        for(Element e:tbodyEles){
            Map map = new HashMap();
            Elements trEles = e.select("tr:has(td.time)");
            if (null != trEles && trEles.size() != 0) {
                String workTime = trEles.get(0).select("td.time").text();
                String[] timeArr = workTime.split("-");

                String start_date = timeArr[0].replaceAll("/","-");

                String end_date = timeArr[1].replaceAll("/","-");
                String company = trEles.get(0).select("td:has(span)").text();
                String position = trEles.get(2).select("td:has(strong)").text();
                String duty = e.select("td:containsOwn(工作描述) + td").html();

                map.put("start_date", start_date);
                map.put("end_date", end_date);
                map.put("company", company);
                map.put("position", position);
                map.put("duty", duty);
            }

            worksList.add(map);
        }


        return worksList;
    }




    public static List<Map<String, String>> htmlED2MapQcwy(String source){

        List<Map<String, String>> edusList = new ArrayList<>();
        Document document = Jsoup.parse(source);
        Elements tbodyEles = document.select("tbody:has(tbody:contains(专业描述))");
        for(Element e:tbodyEles){
            Map map = new HashMap();

            Elements trEles = e.select(">tr");

            String eduTime = trEles.get(0).select("td.time").text();
            String[] timeArr = eduTime.split("-");

            String start_date = timeArr[0].replaceAll("/","-");
            String end_date = timeArr[1].replaceAll("/","-");
            String school = trEles.get(0).select("td.rtbox").text();

            String major_degree_str = trEles.get(1).text();
            String [] major_degreeArr = major_degree_str.split("\\|");
            String major = major_degreeArr[1];
            String degree = major_degreeArr[0];

            map.put("start_date", start_date);
            map.put("end_date", end_date);
            map.put("school", school);
            map.put("major", major);
            map.put("degree", degree);

            edusList.add(map);
        }


        return edusList;
    }



    public static List<Map<String, String>> htmlPD2MapQcwy(String source){

        List<Map<String, String>> projectsList = new ArrayList<>();
        Document document = Jsoup.parse(source);
        Elements tbodyEles = document.select("tbody:has(tbody:contains(项目描述))");
        for(Element e:tbodyEles){
            Map map = new HashMap();

            String time = e.select("td.time").text();
            String[] timeArr = time.split("-");

            String start_date = timeArr[0].replaceAll("/","-");
            String end_date = timeArr[1].replaceAll("/","-");
            String projectname = e.select("td.rtbox").text();
            String description = e.select("td:containsOwn(项目描述) + td").html();



            map.put("description",description);
            map.put("start_date", start_date);
            map.put("projectname", projectname);
            map.put("description", description);


            projectsList.add(map);
        }


        return projectsList;
    }






     public static String getNumFromStr(String input){
         String regEx="[^0-9]";
         Pattern p = Pattern.compile(regEx);
         Matcher m = p.matcher(input);
         return m.replaceAll("").trim();
     }







    public static void main(String[] args) {
        String str = "17年工作经验";

        String regEx="[^0-9]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        System.out.println( m.replaceAll("").trim());


    }


}
